package com.yami.shop.groupbuy.comment.listener;

import com.esotericsoftware.minlog.Log;
import com.yami.shop.bean.event.ProdChangeEvent;
import com.yami.shop.bean.model.Product;
import com.yami.shop.groupbuy.comment.model.GroupTeam;
import com.yami.shop.groupbuy.comment.service.GroupActivityService;
import com.yami.shop.groupbuy.comment.service.GroupTeamService;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Objects;


/**
 * @author Yami
 */
@Slf4j
@Component("groupbuyProdChangeListener")
@AllArgsConstructor
public class ProdChangeListener {

    private final GroupActivityService groupActivityService;
    private final GroupTeamService groupTeamService;

    @EventListener(ProdChangeEvent.class)
    public void prodChangeEvent(ProdChangeEvent event) {
        // 删除的商品的时候，处理已经开团但是未成团的
        // 已经成团的订单按正常流程处理
        // 实际上不需要处理，开启定时任务后，如果开团成功后，删除掉商品，
        // 则拼团不会成功，则会自动退款，
        // 这里如果处理退款，有一定得几率和定时任务处理退款同时运行，所以这里不处理退款
//        handleGroupBugAfterDeleteProd(event);

    }

    /**  删除商品时，处理团购相关 */
    private void handleGroupBugAfterDeleteProd(ProdChangeEvent event) {
        Product product = event.getProduct();
        Long prodId = product.getProdId();
        if (Objects.isNull(prodId)) {
            return;
        }
        // 查询出所有已开团，待成团的订单，
        List<GroupTeam> groupTeams = groupTeamService.getNotGroupTeamByProdId(prodId);
        if (CollectionUtils.isEmpty(groupTeams)) {
            return;
        }
        // 处理未成团的拼团团队，返回退款单列表
        for (GroupTeam groupTeam : groupTeams) {
            groupTeamService.updateNotGroupTeam(groupTeam);
        }

        String okStr = true ? "成功" : "失败";
        Log.info("删除商品prodId = " + prodId + "时，同时也去除在分销设置中的商品prodId = "+ prodId + " ，更新" + okStr);
    }

}
